<template>
  <div class="scroll-container">
    <!-- 表信息配置 -->
    <div class="table-info">
      <Form>
        <Row :gutter="8" class="table-info-row">
          <Col :span="4">
            <Form.Item label="表名">
              <Input v-model:value="table.newTableName" placeholder="表名" size="small" />
            </Form.Item>
          </Col>
          <Col :span="8">
            <Form.Item label="注释">
              <Input v-model:value="table.comment" placeholder="表注释" size="small" />
            </Form.Item>
          </Col>
          <Col :span="6">
            <Form.Item label="引擎">
              <Select
                v-model:value="table.engine"
                placeholder="选择引擎"
                size="small"
                style="width: 100%"
              >
                <Select.Option value="InnoDB">InnoDB</Select.Option>
                <Select.Option value="MyISAM">MyISAM</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col :span="6">
            <Form.Item>
              <Button @click="saveTable" type="primary" size="small">保存</Button>
              <Divider type="vertical" />
              <Button @click="preview" type="primary" size="small">查看</Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </div>
    <Form layout="vertical">
      <!-- 表头 -->
      <Row class="header-row">
        <Col :span="1"> </Col>
        <Col :span="4">列名</Col>
        <Col :span="4">类型</Col>
        <!-- <Col :span="2">长度</Col> -->
        <Col :span="1">主键</Col>
        <Col :span="1">自增</Col>
        <Col :span="1">可空</Col>
        <Col :span="3">默认值</Col>
        <Col :span="8">注释</Col>
        <Col :span="1">操作</Col>
      </Row>

      <!-- 动态列配置 -->
      <draggable
        v-model="table.columns"
        group="form-draggable"
        handle=".drag-handle"
        item-key="id"
      >
        <template #item="{ element, index }">
          <Row class="dynamic-row" :gutter="8" :key="element.id">
            <Col :span="1" class="drag-handle">☰</Col>
            <Col :span="4">
              <Input v-model:value="element.name" placeholder="列名" size="small" />
            </Col>
            <Col :span="4">
              <AutoComplete
                style="width: 100%"
                v-model:value="element.type"
                :options="mysqlTypes"
                placeholder="请输入类型"
                size="small"
                :filter-option="filterOption"
              />
            </Col>
            <!-- <Col :span="2">
              <Input
                v-model:value="element.length"
                placeholder="长度"
                :min="1"
                size="small"
              />
            </Col> -->
            <Col :span="1">
              <Switch v-model:checked="element.isPrimary" size="small" />
            </Col>
            <Col :span="1">
              <Switch v-model:checked="element.isAutoIncrement" size="small" />
            </Col>
            <Col :span="1">
              <Switch v-model:checked="element.isNull" size="small" />
            </Col>
            <Col :span="3">
              <Input v-model:value="element.default" placeholder="默认值" size="small" />
            </Col>
            <Col :span="8">
              <Input v-model:value="element.comment" placeholder="注释" size="small" />
            </Col>
            <Col :span="1">
              <Button type="link" @click="removeColumn(index)" size="small">删除</Button>
            </Col>
          </Row>
        </template>
      </draggable>

      <!-- 添加列按钮 -->
      <Row class="header-row">
        <Col :span="24">
          <Button type="dashed" block @click="addColumn" size="small">+ 添加列</Button>
        </Col>
      </Row>
    </Form>
  </div>
  <Modal v-model:visible="executeModalVisible" title="sql预览" @ok="handleOk">
    <Textarea
      v-model:value="executeSql"
      :auto-size="{ minRows: 6 }"
      placeholder="请输入SQL"
    />
  </Modal>
</template>

<script setup>
import { ref, watch, reactive, defineProps, defineEmits } from "vue";
import {
  Button,
  Form,
  Row,
  Col,
  Input,
  Select,
  Switch,
  AutoComplete,
  Divider,
  Modal,
  Textarea,
  message,
} from "ant-design-vue";
import draggable from "vuedraggable";

// props 接收外部传入的表格配置，支持双向绑定
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
  onTableAction: {
    type: Function, // 自动补全接口方法
    required: true,
  },
});

// 初始化表配置
const table = reactive(
  props.modelValue || {
    dsId: 0,
    databaseName: "",
    name: "", // 表名
    newTableName: "",
    comment: "", // 表注释
    engine: "InnoDB", // 默认引擎
    columns: [
      {
        id: Date.now() + Math.random(),
        name: "",
        type: "VARCHAR",
        length: "255",
        isPrimary: false,
        isAutoIncrement: false,
        isNull: true,
        default: "",
        comment: "",
      },
    ],
  }
);

const emits = defineEmits(["update:modelValue", "preview", "create"]);

const optionsVal = (str) => {
  return {
    value: str,
  };
};

// 内部列数据
const mysqlTypes = ref([
  optionsVal("int"),
  optionsVal("int unsigned"),
  optionsVal("varchar"),
  optionsVal("text"),
  optionsVal("date"),
  optionsVal("datetime"),
  optionsVal("timestamp"),
  optionsVal("float"),
  optionsVal("float unsigned"),
  optionsVal("double"),
  optionsVal("double unsigned"),
  optionsVal("decimal"),
  optionsVal("decimal unsigned"),
  optionsVal("blob"),
  optionsVal("char"),
  optionsVal("tinyint"),
  optionsVal("tinyint unsigned"),
  optionsVal("smallint"),
  optionsVal("smallint unsigned"),
  optionsVal("mediumint"),
  optionsVal("mediumint unsigned"),
  optionsVal("bigint"),
  optionsVal("bigint unsigned"),
  optionsVal("bit"),
  optionsVal("boolean"),
  optionsVal("enum"),
  optionsVal("set"),
  optionsVal("json"),
]);

const filterOption = (input, option) => {
  return option.value.toUpperCase().indexOf(input.toUpperCase()) >= 0;
};

// 监听内部 columns 的变化，并更新外部 columns 数据
watch(
  table,
  (newVal) => {
    emits("update:modelValue", newVal);
  },
  { deep: true }
);

// 添加新列
const addColumn = () => {
  table.columns.push({
    id: Date.now() + Math.random(),
    name: "",
    type: "varchar(255)",
    length: "255",
    isPrimary: false,
    isAutoIncrement: false,
    isNull: true,
    default: "",
    comment: "",
  });
};

// 删除列
const removeColumn = (index) => {
  table.columns.splice(index, 1);
  updateTable();
};

// 预览数据
const preview = () => {
  emits("preview", table);
};

const executeModalVisible = ref(false);
const executeSql = ref("");
const handleOk = async () => {
  if (/^\s*$/.test(executeSql.value)) {
    message.error("请输入sql");
    return;
  }

  const res = await props.onTableAction("execute", {
    dsId: table.dsId,
    databaseName: table.databaseName,
    sql: executeSql.value,
  });

  message.success("执行成功");

  executeModalVisible.value = false;
};

const saveTable = async () => {
  console.log(table);

  if (!table.name || table.name === "") {
    const res = await props.onTableAction("create", table);
    emits("create", true);
  } else {
    const res = await props.onTableAction("save", table);

    executeSql.value = res;
    executeModalVisible.value = true;
  }
};
</script>

<style scoped>
.scroll-container {
  overflow-x: auto;
  padding: 16px;
  max-width: 100%;
  border: 1px solid #dcdcdc;
  border-radius: 8px;
  background-color: #fff;
}

.header-row,
.dynamic-row {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  width: 800px;
  margin-bottom: 5px;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 5px;
}

.col {
  padding: 0 4px;
}

.drag-handle {
  cursor: move;
  font-size: 18px;
  text-align: center;
}
</style>
